package com.yint.http.call;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.yint.http.request.Request;
import com.yint.http.ssl.DefaultHostnameVerifier;
import com.yint.http.ssl.DefaultX509TrustManager;

/**
 * https 请求客户端
 * 
 * @author 殷田
 *
 */
public class HttpsCall extends DefaultCall
{
	public HttpsCall( Request request )
	{
		super( request );
	}

	@Override
	protected HttpURLConnection onGetConnect( SSLSocketFactory factory, String urlStr ) throws IOException
	{
		if ( factory == null )
		{
			HttpsURLConnection.setDefaultHostnameVerifier( new DefaultHostnameVerifier() );
		}
		HttpsURLConnection conn = ( HttpsURLConnection ) new URL( urlStr ).openConnection();
		SSLSocketFactory mFactory = factory == null ? getSSLSocketFactory() : factory;
		if ( mFactory != null )
		{
			conn.setSSLSocketFactory( mFactory );
		}
		return conn;
	}

	/**
	 * 获取一个忽略验证的 SSLSocketFactory
	 * 
	 * @return
	 */
	private SSLSocketFactory getSSLSocketFactory()
	{
		try
		{
			SSLContext sslContext = SSLContext.getInstance( "TLS" );
			sslContext.init( null, new TrustManager[] { new DefaultX509TrustManager() }, null );
			return sslContext.getSocketFactory();
		}
		catch ( Exception e )
		{
			e.printStackTrace();
		}
		return null;
	}
}
